package net.dreamlu.api.oauth;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import net.dreamlu.api.util.OathConfig;
import net.dreamlu.api.util.TokenUtil;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;

/**
 * OauthBaidu BAE
 * email: 596392912@qq.com
 * site:  http://www.dreamlu.net
 * @author L.cm
 * @date Jun 26, 2013 11:25:58 PM
 */
public class OauthBaidu extends Oauth {

	private static final Logger log = Logger.getLogger(OauthBaidu.class);

	private static final String AUTH_URL = "https://openapi.baidu.com/oauth/2.0/authorize";
    private static final String TOKEN_URL = "https://openapi.baidu.com/oauth/2.0/token";
    private static final String USER_INFO_URL = "https://openapi.baidu.com/rest/2.0/passport/users/getInfo";
    
	public OauthBaidu() {
		super();
		setClientId(OathConfig.getValue("openid_baidu"));
		setClientSecret(OathConfig.getValue("openkey_baidu"));
		setRedirectUri(OathConfig.getValue("redirect_baidu"));
	}
    
	/**
	 * 获取授权url
	 * @param @return    设定文件
	 * @return String    返回类型
	 * @throws
	 */ 
	public String getAuthorizeUrl() {
		Map<String, String> params = new HashMap<String, String>();
		params.put("response_type", "code");
		params.put("client_id", getClientId());
		params.put("redirect_uri", getRedirectUri());
		return super.getAuthorizeUrl(AUTH_URL, params);
	}
    
	/**
	 * 获取token
	 * @param @param code
	 * @param @return    设定文件
	 * @return String    返回类型
	 * @throws
	 */
	public String getTokenByCode(String code) throws IOException{
		Map<String, String> params = new HashMap<String, String>();
		params.put("code", code);
		params.put("client_id", getClientId());
		params.put("client_secret", getClientSecret());
		params.put("grant_type", "authorization_code");
		params.put("redirect_uri", getRedirectUri());
		String token = TokenUtil.getAccessToken(super.doPost(TOKEN_URL, params));
		log.error(token);
		return token;
	}
	
	/**
	 * 获取UserInfo
	 * @return    设定文件
	 * @return String    返回类型
	 * @throws
	 */
	public String getUserInfo(String accessToken) throws IOException{
		Map<String, String> params = new HashMap<String, String>();
		params.put("access_token", accessToken);
		return super.doPost(USER_INFO_URL, params);
	}
	
	/**
	 * 根据code一步获取用户信息
	 * @param @param args    设定文件
	 * @return void    返回类型
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	public Map<String, String> getUserInfoByCode(String code) throws IOException{
		String accessToken = getTokenByCode(code);
		String userInfo = getUserInfo(accessToken);
		log.error(userInfo);
		return JSON.parseObject(userInfo, Map.class);
	}
}
